using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http;
using Terra.WebApi;

namespace Terra.IntegrationTests.TestBase;

/// <summary>
/// 集成测试基类，提供HTTP客户端和测试服务器
/// </summary>
public abstract class IntegrationTestBase : IDisposable
{
    protected readonly TestServer TestServer;
    protected readonly HttpClient Client;
    protected readonly IServiceProvider ServiceProvider;

    protected IntegrationTestBase()
    {
        var builder = new WebHostBuilder()
            .UseEnvironment("Testing")
            .ConfigureAppConfiguration((context, config) =>
            {
                config.AddJsonFile("appsettings.Testing.json", optional: false)
                      .AddEnvironmentVariables();
            })
            .UseStartup<Startup>();

        TestServer = new TestServer(builder);
        Client = TestServer.CreateClient();
        ServiceProvider = TestServer.Services;
    }

    /// <summary>
    /// 获取服务
    /// </summary>
    protected T GetService<T>() where T : class
    {
        return ServiceProvider.GetRequiredService<T>();
    }

    /// <summary>
    /// 获取数据库上下文
    /// </summary>
    protected async Task<T> GetDbContextAsync<T>() where T : class
    {
        using var scope = ServiceProvider.CreateScope();
        return scope.ServiceProvider.GetRequiredService<T>();
    }

    public void Dispose()
    {
        Client.Dispose();
        TestServer.Dispose();
    }
}